/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain (a) copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.kizitonwose.calendarview.utils;

import java.util.*;

/**
 * IterableExtension
 *
 * @version 1.0
 * @date 2021/2/22/022 11:10
 */
public class IterableExtension<E> {
    private Collection<E> collection;

    public IterableExtension(Collection<E> collection) {
        this.collection = collection;
    }

    /**
     * 获取IterableExtension对象
     *
     * @param collection Collection<E>
     * @param <E> 泛型E
     * @return IterableExtension<E>
     */
    public static <E> IterableExtension<E> getInstance(Collection<E> collection) {
        return new IterableExtension<>(collection);
    }

    public Collection<E> getCollection() {
        return collection;
    }

    /**
     * 获取map集合
     *
     * @param keySelector Convert<E, K>
     * @param <K> 泛型K
     * @return Map<K, List<E>>
     */
    public <K> Map<K, List<E>> groupBy(Convert<E, K> keySelector) {
        Map<K, List<E>> map = new LinkedHashMap<>();
        for (E e : collection) {
            K key = keySelector.convert(e);
            List<E> list = getOrPut(map, key, new ArrayList<>());
            list.add(e);
        }
        return map;
    }

    private <K, V> V getOrPut(Map<K, V> map, K key, Object defaultValue) {
        V value = map.get(key);
        if (value == null) {
            V answer = (V) defaultValue;
            map.put(key, answer);
            return answer;
        } else {
            return value;
        }
    }

    /**
     * 根据separator构造新的字符串
     *
     * @param separator String
     * @param convert  Convert<E, V>
     * @param <V> 泛型V
     * @return String result
     */
    public <V> String joinToString(String separator, Convert<E, V> convert) {
        StringBuilder result = new StringBuilder();
        if (collection != null && convert != null) {
            for (E e : collection) {
                if (result.length() > 0) {
                    result.append(separator);
                }
                result.append(convert.convert(e));
            }
        }
        return result.toString();
    }

    /**
     * 转换
     *
     * @param <T> 泛型T
     * @param <V> 泛型V
     */
    public interface Convert<T, V> {
        V convert(T t);
    }


}
